import { Injectable } from '@nestjs/common';
import { CartsEntity } from '../entities';
import { In, Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateCartDto } from '../dto/create_cart.dto';
import { User } from '@/modules/User/types';
import { GoodService } from './good.service';
import { UserService } from '@/modules/User/service';
import { UpdateCartDto } from '../dto/update_cart.dto';
import { MutilUpdateCart } from '../dto/mutil_update_cart.dto';

@Injectable()
export class CartsService {
  constructor(
    @InjectRepository(CartsEntity)
    private readonly cartsRepository: Repository<CartsEntity>,
    private readonly goodService: GoodService,
    private readonly userService: UserService,
  ) {}
  async create(user: User, body: CreateCartDto) {
    // 首先根据good_id和当前用户id查询购物车数据是否存在
    // 如果存在将购物车中的数量加1
    // 如果不存在创建购物车数据
    const cart = await this.cartsRepository.findOne({
      where: {
        good: {
          id: body.good,
        },
        user: {
          id: user.userId,
        },
      },
    });
    try {
      if (cart) {
        cart.num += 1;
        await cart.save();
      } else {
        const cart = this.cartsRepository.create();
        const curUser = await this.userService.detail(user.userId);
        const good = await this.goodService.detail(body.good);
        cart.user = curUser;
        cart.good = good;
        cart.num = body.num;
        cart.is_select = body.is_select;
        await cart.save();
      }
      return {
        statusCode: 200,
        message: '添加购物车成功',
      };
    } catch (error) {
      console.log(error);
      return {
        statusCode: 500,
        message: '添加购物车失败',
      };
    }
  }

  async list(user: User) {
    const carts = await this.cartsRepository.find({
      where: {
        user: {
          id: user.userId,
        },
      },
      relations: ['good', 'good.media'],
    });
    return carts;
  }
  async update(id: string, body: UpdateCartDto) {
    const cart = await this.cartsRepository.findOneOrFail({
      where: {
        id,
      },
    });
    cart.num = body.num;
    cart.is_select = body.is_select;
    return await cart.save();
  }
  async mutilUpdate(body: MutilUpdateCart[]) {
    const ids = body.map((item) => item.id);
    const carts = await this.cartsRepository.findByIds(ids);
    carts.forEach((cart) => {
      const item = body.find((item) => item.id === cart.id);
      cart.num = item.num;
      cart.is_select = item.is_select;
    });
    return await this.cartsRepository.save(carts);
  }
}
